package com.qingyun.web.controller.pcapi.shop;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.qingyun.common.annotation.Log;
import com.qingyun.common.annotation.RepeatSubmit;
import com.qingyun.common.constant.Constants;
import com.qingyun.common.core.domain.AjaxResult;
import com.qingyun.common.core.domain.model.TiktokProxyVo;
import com.qingyun.common.core.validate.AddGroup;
import com.qingyun.common.core.validate.EditGroup;
import com.qingyun.common.enums.BusinessType;
import com.qingyun.common.utils.poi.ExcelUtil;
import com.qingyun.security.controller.BaseController;
import com.qingyun.security.utils.SecurityUtils;
import com.qingyun.shop.domain.TiktokProxy;
import com.qingyun.shop.domain.TiktokShop;
import com.qingyun.shop.domain.TiktokTransfer;
import com.qingyun.shop.domain.TiktokUserProxy;
import com.qingyun.shop.domain.bo.TiktokProxyBo;
import com.qingyun.shop.mapper.TiktokTransferMapper;
import com.qingyun.shop.mapper.TiktokUserProxyMapper;
import com.qingyun.shop.service.ITiktokProxyService;
import com.qingyun.shop.service.ITiktokShopService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import javax.validation.constraints.NotEmpty;
import javax.validation.constraints.NotNull;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

/**
 * 代理组织Controller
 *
 * @author qingyun
 * @date 2021-09-04
 */
@Validated
@Api(value = "代理组织控制器", tags = {"^代理组织管理"})
@AllArgsConstructor
@RestController
@RequestMapping("/system/proxy/org")
public class TiktokProxyController extends BaseController {

    private final ITiktokProxyService iTiktokProxyService;

    private final TiktokUserProxyMapper userProxyMapper;

    private final ITiktokShopService tiktokShopService;

    private final TiktokTransferMapper transferMapper;
	/**
	 * 查询代理组织列表
	 */
	@ApiOperation("查询代理组织列表 system:proxy:list")
	@PreAuthorize("@ss.hasPermi('system:proxy:list')")
	@GetMapping("/list")
    public AjaxResult<List<TiktokProxyVo>> list(@Validated TiktokProxyBo bo){
		List<TiktokProxyVo> tiktokProxyVos = iTiktokProxyService.queryTreeList(bo);
	//List<TiktokProxyVo> tiktokProxyVos = iTiktokProxyService.queryList(bo);
		return AjaxResult.success(tiktokProxyVos);
	}

    /**
     * 导出代理组织列表
     */
    @ApiOperation("导出代理组织列表 system:proxy:export")
    @PreAuthorize("@ss.hasPermi('system:proxy:export')")
    @GetMapping("/export")
    public void export(@Validated TiktokProxyBo bo, HttpServletResponse response) {
        List<TiktokProxyVo> list = iTiktokProxyService.queryList(bo);
        ExcelUtil.exportExcel(list, "代理组织", TiktokProxyVo.class, response);
    }

    /**
     * 获取代理组织详细信息
     */
    @ApiOperation("获取代理组织详细信息 system:proxy:query")
    @PreAuthorize("@ss.hasPermi('system:proxy:query')")
    @GetMapping("/{id}")
    public AjaxResult<TiktokProxyVo> getInfo(@NotNull(message = "主键不能为空")
                                                  @PathVariable("id") Long id) {
        return AjaxResult.success(iTiktokProxyService.queryById(id));
    }


    @PreAuthorize("@ss.hasPermi('system:proxy:edit')")
    @ApiOperation("代理商开关 system:proxy:edit")
    @GetMapping("/state")
    public AjaxResult state(Long proxyId,Integer status){
		if (SecurityUtils.isProxy()&&SecurityUtils.getProxy().getId().equals(proxyId)) {
		    return AjaxResult.error("不能修改自己状态");
		}
		boolean update = iTiktokProxyService.update(Wrappers.lambdaUpdate(TiktokProxy.class).set(TiktokProxy::getStatus, status).eq(TiktokProxy::getId, proxyId));
		return toAjax(update);
	}

    /**
     * 新增代理组织
     */
    @ApiOperation("新增代理组织 system:proxy:add")
    @PreAuthorize("@ss.hasPermi('system:proxy:add')")
    @Log(title = "代理组织", businessType = BusinessType.INSERT)
    @RepeatSubmit()
    @PostMapping()
    public AjaxResult<Void> add(@Validated(AddGroup.class) @RequestBody TiktokProxyBo bo) {
        return toAjax(iTiktokProxyService.insertByBo(bo) ? 1 : 0);
    }

    /**
     * 修改代理组织
     */
    @ApiOperation("修改代理组织 system:proxy:list:edit")
	@PreAuthorize("@ss.hasPermi('system:proxy:list:edit')")
    @RepeatSubmit()
    @PutMapping()
    public AjaxResult<Void> edit(@Validated(EditGroup.class) @RequestBody TiktokProxyBo bo) {
        return toAjax(iTiktokProxyService.updateByBo(bo) ? 1 : 0);
    }

	@ApiOperation("查询代理下用户数量")
    @GetMapping("proxyUserCount")
    public AjaxResult<Integer> userCount(Long proxyId){
		Integer integer = userProxyMapper.selectCount(Wrappers.lambdaQuery(TiktokUserProxy.class).eq(TiktokUserProxy::getProxyId, proxyId));
		return AjaxResult.success(integer);
	}

    /**
     * 删除代理组织
     */
    @ApiOperation("删除代理组织 system:proxy:remove")
    @PreAuthorize("@ss.hasPermi('system:proxy:remove')")
    @Log(title = "代理组织" , businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}/{inherit}")
    public AjaxResult<Void> remove(@NotEmpty(message = "主键不能为空")
                                       @PathVariable Long[] ids,@PathVariable() Boolean inherit) {
        return toAjax(iTiktokProxyService.deleteWithValidByIds(Arrays.asList(ids), true,inherit) ? 1 : 0);
    }


    @PreAuthorize("@ss.hasPermi('system:proxy:transfer')")
    @ApiOperation("代理商用户给商家转视频转发余额 system:proxy:transfer")
    @PostMapping("/transferVideoCount")
    public AjaxResult transfer(Long shopId,Long videoCount){
		Boolean transfer = iTiktokProxyService.transfer(shopId, videoCount);
		return toAjax(transfer);
	}

    @ApiOperation("获取代理商的视频转发余额")
    @GetMapping("/getProxyVideoCount")
    public AjaxResult getProxyVideoCount() {
        Long videoCount = iTiktokProxyService.selectVideoCount();
        return AjaxResult.success(videoCount);
    }


	@PreAuthorize("@ss.hasPermi('system:admin:addVideoCount')")
	@ApiOperation("管理员给代理或者商家充值 system:admin:addVideoCount")
	@PostMapping("addVideCount")
	public AjaxResult addVideoCount(Long publicId,Long videoCount,Long type){

        TiktokTransfer transfer = new TiktokTransfer();

        if (SecurityUtils.isManager()) {
            transfer.setProxyId(1L);
            transfer.setProxyName("总代理");
        } else {
            transfer.setProxyId(SecurityUtils.getProxy().getId());
            transfer.setProxyName(SecurityUtils.getProxy().getName());
        }

        transfer.setVideoCount(String.valueOf(videoCount));
        transfer.setCreateTime(new Date());


        if (type.equals(Constants.PROXY)) {
			TiktokProxy tiktokproxy = iTiktokProxyService.getById(publicId);
			tiktokproxy.setVideoCount(tiktokproxy.getVideoCount()+videoCount);
			transfer.setShopId(0L);
			transfer.setShopName(iTiktokProxyService.queryById(publicId).getName());
			iTiktokProxyService.updateById(tiktokproxy);
		}else if(type.equals(Constants.SHOP)){
			TiktokShop tiktokShop = tiktokShopService.getById(publicId);
			tiktokShop.setVideoCount(tiktokShop.getVideoCount()+videoCount);
			transfer.setShopName(tiktokShopService.queryById(publicId).getName());
			transfer.setShopId(publicId);
			tiktokShopService.updateById(tiktokShop);
		}
		transferMapper.insert(transfer);
    	return AjaxResult.success();
	}
}
